<?PHP
 if (isset($_SERVER['SERVER_SOFTWARE'])) {
  die("This is not a public page\n");
 }

 require_once(dirname(__FILE__) . '/inc/database.php');
 require_once(dirname(__FILE__) . '/inc/plugin.php');

 $pi = getPluginInfo($argv[1]);

 if ($pi === false || $pi === null) {
  die("Plugin info couldn't be read\n"); 
 }

 $id = getField($pi, 'addonid');
 $version = getField($pi, 'friendlyversion');
 $fversion = getField($pi, 'version');
 
 if ($id === null) { die("Couldn't read addon ID\n"); }
 if ($version === null) { die("Couldn't read friendly version\n"); }
 if ($fversion === null) { die("Couldn't read version\n"); }

 $sql  = 'SELECT version_id, version_stable FROM versions WHERE addon_id = ' . $id;
 $sql .= ' AND version_unstable = 1';
 $res  = mysql_query($sql);

 $new = false;
 if (mysql_num_rows($res) == 0) {
  $new = true;
 } else {
  $row = mysql_fetch_assoc($res);
  if ((int) $row['version_stable'] == 1) {
   $sql = 'UPDATE versions SET version_unstable = 0 WHERE version_id = ' . $row['version_id'];
   mysql_query($sql);
   $new = true;
  } else {
   $vid = $row['version_id'];
  }
 }

 if ($new) {
  $sql = 'INSERT INTO versions (addon_id, version_unstable) VALUES (' . $id . ', 1)';
  mysql_query($sql);
  $vid = mysql_insert_id();
 }

 $sql  = 'UPDATE versions SET version_fileversion = ' . $fversion . ', version_version = \'' . m($version) . '\', version_download = \'';
 $sql .= m(file_get_contents($argv[1])) . '\' WHERE version_id = ' . $vid;
 mysql_query($sql);
 
?>
